<template>
  <view class="pages">
    <u-sticky offset-top="0" zIndex="10000">
      <up-navbar
        title="体重记录"
        :autoBack="true"
        :placeholder="true"
        bgColor="#F5EFFD"
        :titleStyle="titleStyle"
        :leftIconSize="26"
      >
      </up-navbar>
    </u-sticky>
    <view class="today_weight_box">
      <view class="today_weight_title" v-if="weightRecordList.length"
        >今日 {{ `(${gestationValue})` }} 体重</view
      >
      <view class="today_weight_title" v-else>
        {{ `今日（${today_user_pre}）体重` || '今日（孕3周+1天）体重' }}
      </view>
      <view v-if="weightRecordList.length && todayWeightValue != 0">
        <view style="margin: 16rpx 0; text-align: center">
          <text
            class="today_weight_value"
            :style="{ marginLeft: todayWeightValue.toString().length == 2 ? '30rpx' : '' }"
          >
            {{ todayWeightValue || '' }}
          </text>
          <text style="font-size: 20rpx; color: #777777; margin-left: 10rpx">公斤</text>
        </view>
        <view class="today_weight_bottom">
          <view style="font-size: 22rpx; color: #777777">比孕前体重{{ beforeWeight }}kg</view>
          <view style="font-size: 26rpx; color: #333333; margin-top: 6rpx"
            >{{ `${addAndDecrease}${compareValue}` }}kg
          </view>
        </view>
      </view>
      <view
        v-if="!weightRecordList.length"
        style="font-size: 34rpx; color: #777777; margin-top: 30rpx; margin-bottom: 6rpx"
        >暂未记录</view
      >
      <view
        v-if="weightRecordList.length && todayWeightValue == 0"
        style="font-weight: 600; font-size: 40rpx; color: #999999; margin-top: 20rpx"
        >未记录</view
      >
    </view>
    <view
      class="weight_record_box"
      :style="{ minHeight: weightRecordHeight }"
      scroll-y
      @scrolltolower="loadMore()"
    >
      <view class="weight_record_title">
        <view class="record_date_title">记录日期</view>
        <view>体重</view>
        <view class="exponent_title" :style="{ justifyContent: !isShowBtn ? 'center' : '' }">
          <text style="margin-right: 10rpx">增长量</text>
          <up-icon name="question-circle" color="#2C2C2C" size="20" @click="exponentRule"></up-icon>
        </view>
      </view>
      <view v-if="weightRecordList.length">
        <scroll-view
          class="scroll-v"
          :style="{ height: weightRScrollHeight }"
          @scrolltolower="loadMore()"
          scroll-y
        >
          <view>
            <view class="record_list_box" v-for="(item, index) in weightRecordList" :key="index">
              <view class="record_time_box">
                <view class="record_date">{{ item?.date }}</view>
                <view class="record_time"
                  ><text>{{ item?.add_time }}</text> {{ item?.user_pre }}</view
                >
              </view>
              <view class="record_weight">{{ item?.num }}</view>
              <view
                class="record_exponent_box"
                :style="{ justifyContent: !isShowBtn ? 'center' : '' }"
              >
                <view class="record_exponent" :style="{ marginRight: !isShowBtn ? '30rpx' : '' }">{{
                  item?.change_weight
                }}</view>
                <image
                  v-if="isShowBtn"
                  src="@/static/imgs/det_record.png"
                  @click="detRecord(item.id)"
                ></image>
                <image
                  v-if="isShowBtn"
                  src="@/static/imgs/edit_record.png"
                  @click="editRecord(item.id)"
                ></image>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <h-not-list
        v-else
        title="APP内暂无记录"
        defaultHeight="600"
        img="/static/imgs/default_icon_y.png"
      ></h-not-list>
    </view>
    <view v-if="isShowBtn" class="keep_weight" @click="keepWeight">
      <up-icon name="plus" color="#fff" size="20"></up-icon>
      <view>记体重</view>
    </view>
  </view>
  <h-modal
    :show="bindShow"
    :titlea="delWeightRecordTime"
    titleb="的体重记录吗？"
    leftBtn="取消"
    rightBtn="确认"
    @clear="clearEdit"
    @bind="saveEditFn"
  ></h-modal>
  <!-- 体重编辑弹窗 -->
  <u-popup :show="showWeight" :round="10" mode="bottom" @close="showWeight = false">
    <view class="weight_pop_box">
      <view class="time" v-if="addWeightRecord">
        <text class="time_info">{{ todayTime }}</text>
        <text class="time_info" style="margin: 0 8rpx">{{
          weightTimeValue || formatDate(Date.now(), 'HH:mm')
        }}</text>
        <up-icon
          :name="flag ? 'arrow-up-fill' : 'arrow-down-fill'"
          color="#333333"
          size="14"
          @click="handletime"
        ></up-icon>
      </view>
      <view class="time" v-else>
        <text class="time_info">{{ todayTime }}</text>
        <text class="time_info" style="margin: 0 8rpx">{{
          weightTimeValue || formatDate(Date.now(), 'HH:mm')
        }}</text>
      </view>
      <view class="weight_pop_close" @click="weightPopClose">
        <up-icon name="close" color="#333333" size="20"></up-icon>
      </view>
      <numberKeyboard
        v-if="!addWeightRecord"
        :inputValueD="eidnValue"
        @saveInput="saveWeight"
      ></numberKeyboard>
      <numberKeyboard v-else @saveInput="saveWeight"></numberKeyboard>
    </view>
  </u-popup>
  <!-- 时间选择弹窗 -->
  <u-popup :show="showTimePicker" :round="10" mode="bottom" @close="closetimepicker">
    <view>
      <view class="time">
        <text class="time_info">{{ todayTime }}</text>
        <text class="time_info" style="margin: 0 8rpx">{{
          weightTimeValue || formatDate(Date.now(), 'HH:mm')
        }}</text>
      </view>
      <view style="margin-top: 50rpx">
        <h-picker-dateTime
          :showValue="false"
          @changeTime="weightTimeChange"
          @confirm="weightTimeVerify"
          :value="formatDate(Date.now(), 'YYYY-MM-DD HH:mm')"
        ></h-picker-dateTime>
      </view>
    </view>
  </u-popup>
  <!-- 指数规则弹窗 -->
  <u-popup
    :show="showExponent"
    :safeAreaInsetBottom="false"
    mode="center"
    @touchmove.stop.prevent="moveHandle"
    @close="showExponent = false"
    :round="10"
  >
    <view class="warn_box">
      <view class="warn_main"
        >增长量：是指该条数据记录的体重数值与孕前体重相比，增长或下降的差值，“+”表示比孕前上涨，“-”表示比孕前下降</view
      >
      <view>
        <u-button
          type="primary"
          @click="saveEualuation"
          shape="circle"
          text="我知道了"
          class="custom_style"
        ></u-button>
      </view>
    </view>
  </u-popup>
  <!--  <u-popup
    :show="showExponent"
    :round="10"
    mode="bottom"
    @close="showExponent = false"
    :closeable="true"
  >
    <view class="exponent_box">
      <view class="exponent_title">{{ bmiInfoList[0].title }}</view>
      <view class="calculation_rule">{{ bmiInfoList[1].title }}</view>
      <view class="radius_list">
        <view class="radius_list_title">
          <view class="list_main" v-for="(item, index) in bmiInfoList[2]" :key="index">{{
            item.title
          }}</view>
        </view>
        <view class="radius_list_main">
          <view>
            <view class="list_main" v-for="(i, n) in bmiInfoList[2][0].content" :key="n">{{
              i
            }}</view>
          </view>
          <view>
            <view class="list_main" v-for="(e, z) in bmiInfoList[2][1].content" :key="z">{{
              e
            }}</view>
          </view>
        </view>
      </view>
      <view class="look_out">
        不过需要注意的是，这个范围只适用于年满18岁的成年人。这个标准虽然可以比较方便快捷地评估出一个人的肥胖程度，但其实不够准确。因为肥胖是根据脂肪在身体内的比例而界定出来的。有的人体重在正常标准之内，但体脂肪的测量值却超过了正常范围，这就是所谓的隐形肥胖。另外，即使体重相同，经常锻炼(如健身教练、运动员)和不经常锻炼的人的肥胖程度也不相同。所以，BMI可以用来粗略界定一个人的肥胖程度，但并不是准确且唯一的评价标准。
      </view>
    </view>
  </u-popup> -->
</template>

<script setup lang="ts">
import { ref } from 'vue'
import numberKeyboard from '@/components/numberKeyboard/numberKeyboard.vue'
import { navigateBack, navigateTo, formatDate, showToast } from '@/utils'
import {
  getRecordWeight,
  changeRecordWeight,
  delRecordWeight,
  setRecordWeight,
  getBmiInfo,
} from '@/api/pregnancy/index'
import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app'
//体重记录高度
const weightRecordHeight = ref('')
const isShowBtn = ref(true)
const titleStyle = ref('font-weight: 500;font-size: 36rpx;color: #333333;')
const todayTime = ref('今天')
const eidnValue = ref('0.0')
const exponentList = ref([
  { radius: '18.5-23.9', class: '正常' },
  { radius: '＜18.5', class: '过轻' },
  { radius: '24.0-27.9', class: '超重' },
  { radius: '≥28', class: '肥胖' },
])
const weightRecordPreams = ref({
  uid: '',
  page: 1,
  limit: 10,
})
//孕期
const gestationValue = ref('')
const todayWeightValue = ref()
const beforeWeight = ref('')
const addAndDecrease = ref('')
const compareValue = ref('')
//体重记录列表
const weightRecordList = ref([])
//指数list
const bmiInfoList = ref([])
//
const bindShow = ref(false)
const showWeight = ref(false)
const showTimePicker = ref(false)
const showExponent = ref(false)
function moveHandle() {
  return false
}
//编辑的时间
const weightTimeValue = ref('')
//体重记录滑动高度
const weightRScrollHeight = ref('')
const userId = ref('')
onLoad((options) => {
  if (options.isshow === false || options.isshow == 'false') {
    isShowBtn.value = false
  } else {
    isShowBtn.value = true
  }
  if (options.uid) {
    userId.value = options.uid
  }
  uni.getSystemInfo({
    success: (e) => {
      console.log(e.windowHeight)
      if (e.windowHeight >= 740 && e.windowHeight < 840) {
        weightRecordHeight.value = `940rpx`
        weightRScrollHeight.value = `855rpx`
      }
      if (e.windowHeight >= 640 && e.windowHeight < 740) {
        weightRecordHeight.value = `740rpx`
        weightRScrollHeight.value = `655rpx`
      }
      if (e.windowHeight >= 840 && e.windowHeight < 900) {
        weightRecordHeight.value = `970rpx`
        weightRScrollHeight.value = `875rpx`
      }
      if (e.windowHeight > 900) {
        weightRecordHeight.value = `1100rpx`
        weightRScrollHeight.value = `1015rpx`
      }
      if (e.windowHeight < 640) {
        weightRecordHeight.value = `640rpx`
        weightRScrollHeight.value = `555rpx`
      }
    },
  })
})
onShow(() => {
  weightRecordPreams.value.page = 1
  last_page.value = 0
  weightRecordList.value = []
  getRecordWeightFn()
  // getBmiInfoFn()
})
const today_user_pre = ref()
const last_page = ref(0)
//获取体重记录
async function getRecordWeightFn() {
  weightRecordPreams.value.uid = userId.value
  const res = await getRecordWeight(weightRecordPreams.value)
  if (res?.code == 200) {
    gestationValue.value = res?.data?.today_user_pre
    todayWeightValue.value = res?.data?.today_record
    today_user_pre.value = res?.data?.today_user_pre
    beforeWeight.value = res?.data?.user_card_weight
    let history_lst = res?.data?.history_lst
    let list = history_lst.data.map((item) => {
      let index = item.add_time.indexOf(' ')
      if (index !== -1 && index + 6 <= item.add_time.length) {
        item.add_time = item.add_time.slice(index + 1, index + 6)
      }
      if (item.change_weight.toString()[0] != '-') {
        item.change_weight = `+${item.change_weight}`
      }
      return item
    })
    last_page.value = history_lst.last_page
    weightRecordList.value =
      weightRecordPreams.value.page < history_lst.last_page
        ? list
        : weightRecordList.value.concat(list)
    weightRecordList.value = [...new Set(weightRecordList.value)]
    if (res.data.gap[0] == '-') {
      addAndDecrease.value = '减少'
      compareValue.value = res.data.gap.slice(1)
    } else {
      addAndDecrease.value = '增加'
      compareValue.value = res.data.gap
    }
  }
}
const delWeightRecord = ref(0)
const delWeightRecordTime = ref('')
function detRecord(id) {
  bindShow.value = true
  weightRecordList.value.forEach((item) => {
    if (item.id == id) {
      delWeightRecordTime.value = `确定要删除${item.date}`
    }
  })
  delWeightRecord.value = id
}
//取消
function clearEdit() {
  bindShow.value = false
}
//编辑
function editRecord(id) {
  addWeightRecord.value = false
  weightRecordList.value.forEach((item) => {
    if (item.id == id) {
      eidnValue.value = item.num
      weightPreams.value.weight_id = id
      weightTimeValue.value = item.add_time
      if (item.date == formatDate(Date.now(), 'YYYY-MM-DD')) {
        todayTime.value = '今天'
      } else {
        todayTime.value = item.date
      }
    }
  })
  showWeight.value = true
}
function saveWeight(e) {
  if (addWeightRecord.value) {
    if (e == '0.0') {
      showToast('您还没有输入体重')
    } else {
      addWeightPreams.value.weight = e
      setRecordWeightFn()
    }
  } else {
    if (e == '0.0') {
      showToast('您还没有编辑体重')
      weightPreams.value.weight = eidnValue.value
    } else {
      weightPreams.value.weight = e
      changeRecordWeightFn()
    }
  }
}
//体重选择参数
const weightPreams = ref({
  type: 2,
  weight: '',
  weight_id: '',
})
//编辑体重
async function changeRecordWeightFn() {
  const res = await changeRecordWeight({ uid: propsuid.value, ...weightPreams.value })
  if (res.code == 200) {
    showToast('修改成功')
    showWeight.value = false
    weightRecordPreams.value.page = 1
    last_page.value = 0
    weightRecordList.value = []
    getRecordWeightFn()
  } else {
    showToast(res.msg)
  }
}
//确认删除
function saveEditFn() {
  let preams = {
    weight_id: delWeightRecord.value,
  }

  delRecordWeightFn(preams)
}
//删除体重
async function delRecordWeightFn(preams) {
  const res = await delRecordWeight({ uid: propsuid.value, ...preams })
  if (res.code == 200) {
    bindShow.value = false
    weightRecordPreams.value.page = 1
    last_page.value = 0
    weightRecordList.value = []
    showToast(res.msg)
    getRecordWeightFn()
  } else {
    showToast(res.msg)
  }
}
//指数规则
function exponentRule() {
  showExponent.value = true
}
//添加体重
const addWeightRecord = ref(false)
//添加体重参数
const addWeightPreams = ref({
  weight: '',
  date: formatDate(Date.now(), 'YYYY-MM-DD'),
  set_time: formatDate(Date.now(), 'YYYY-MM-DD HH:mm'),
})
//记录体重
async function setRecordWeightFn() {
  const res = await setRecordWeight({ uid: propsuid.value, ...addWeightPreams.value })
  if (res?.code == 200) {
    weightRecordPreams.value.page = 1
    last_page.value = 0
    weightRecordList.value = []
    showToast(res.msg)
    showWeight.value = false
    getRecordWeightFn()
  } else {
    showToast(res.msg)
  }
}
//编辑时间
const flag = ref(false)
const handletime = () => {
  showWeight.value = false
  showTimePicker.value = true
  flag.value = !flag.value
}
const closetimepicker = () => {
  showTimePicker.value = false
  flag.value = !flag.value
  showWeight.value = true
}
// 获取指数
// async function getBmiInfoFn() {
//   const res = await getBmiInfo()
//   if (res.code == 200) {
//     let newObj = {}
//     bmiInfoList.value = res.data
//   }
// }
//体重时间选择
function weightTimeChange(e, n) {
  addWeightPreams.value.set_time = e
  todayTime.value = n
  weightTimeValue.value = e.split(' ')[1]
}
//体重时间确认
const isChangeTime = ref(false)
function weightTimeVerify() {
  if (!addWeightPreams.value.set_time) {
    showToast('请选择时间')
  } else {
    isChangeTime.value = true
    showTimePicker.value = false
    flag.value = !flag.value
    showWeight.value = true
    addWeightPreams.value.date = addWeightPreams.value.set_time.split(' ')[0]
    // weightTimeValue.value = addWeightPreams.value.set_time.split(' ')[1]
    // showTimePicker.value = false
    // flag.value = !flag.value
    // showWeight.value = true
    // todayTime.value = weightPreams.value.set_time.split(' ')[0]
  }
}
//关闭体重弹窗
function weightPopClose() {
  showWeight.value = false
}
//记体重
function keepWeight() {
  weightTimeValue.value = ''
  addWeightPreams.value.set_time = formatDate(Date.now(), 'YYYY-MM-DD HH:mm')
  addWeightPreams.value.date = formatDate(Date.now(), 'YYYY-MM-DD')
  showWeight.value = true
  todayTime.value = '今天'
  addWeightRecord.value = true
}
const loadMore = () => {
  if (weightRecordPreams.value.page < last_page.value) {
    weightRecordPreams.value.page++
    getRecordWeightFn()
  }
}
function saveEualuation() {
  showExponent.value = false
}
</script>

<style lang="scss" scoped>
.pages {
  min-height: 100vh;
  background: linear-gradient(180deg, #f5effd 0%, #f6f6f6 100%);
  font-family: PingFang SC, PingFang SC;
  display: flex;
  flex-direction: column;
  align-items: center;

  .today_weight_box {
    width: 702rpx;
    // height: 269rpx;
    background: #ffffff;
    border-radius: 10rpx 10rpx 10rpx 10rpx;
    margin: 10rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    padding: 30rpx 0;

    .today_weight_title {
      font-size: 22rpx;
      color: #333333;
    }

    .today_weight_bottom {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }

  .weight_record_box {
    width: 702rpx;
    // min-height: 900rpx;
    background: #ffffff;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    .scroll-v {
      // height: 815rpx;
      overflow: hidden;
    }
    .weight_record_title {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 85rpx;
      background: #eee9ff;
      border-radius: 10rpx 10rpx 0rpx 0rpx;
      font-size: 28rpx;
      color: #000000;

      .record_date_title {
        width: 220rpx;
        text-align: center;
      }

      .exponent_title {
        width: 210rpx;
        display: flex;
        align-items: center;
      }
    }

    .record_list_box {
      width: 670rpx;
      height: 120rpx;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 24rpx;
      color: #000000;
      border-bottom: 1rpx solid #e6e6e6;

      .record_time_box {
        width: 200rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .record_exponent_box {
        width: 190rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .record_exponent {
          width: 70rpx;
          text-align: center;
        }
        image {
          width: 24rpx;
          height: 24rpx;
        }
      }

      &:last-child {
        border-bottom: none;
      }
    }
  }

  .keep_weight {
    width: 241rpx;
    height: 78rpx;
    background: #a28aff;
    border-radius: 91rpx 91rpx 91rpx 91rpx;
    display: flex;
    align-items: center;
    justify-content: space-around;
    color: #fff;
    font-weight: 600;
    font-size: 28rpx;
    padding: 0 40rpx;
    position: fixed;
    bottom: 60rpx;
  }
}

.time {
  margin-top: 30rpx;
  display: flex;
  justify-content: center;
  font-family: PingFang SC, PingFang SC;

  .time_info {
    font-weight: 600;
    font-size: 28rpx;
    color: #333333;
  }
}
.today_weight_value {
  font-weight: 600;
  font-size: 58rpx;
  color: #333333;
}
.exponent_box {
  width: 690rpx;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  font-family: PingFang SC, PingFang SC;

  .exponent_title {
    font-weight: 600;
    font-size: 36rpx;
    color: #333333;
    margin: 30rpx 0;
  }

  .calculation_rule {
    font-size: 32rpx;
    color: #666666;
    line-height: 50rpx;
  }

  .radius_list {
    margin: 20rpx 0;

    .radius_list_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 32rpx;
      color: #333333;
      margin: 20rpx 0;

      .list_main {
        width: 345rpx;
        padding-left: 20rpx;
      }
    }

    .radius_list_main {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 32rpx;
      color: #666666;

      .list_main {
        width: 345rpx;
        padding-left: 20rpx;
        height: 90rpx;
        border-bottom: 2rpx solid #f6f6f6;
        line-height: 90rpx;
      }
    }
  }

  .look_out {
    font-size: 32rpx;
    color: #666666;
    line-height: 50rpx;
    margin-bottom: 40rpx;
  }
}

.weight_pop_box {
  font-family: PingFang SC, PingFang SC;
  position: relative;
  .time {
    display: flex;
    align-items: center;
  }
  .weight_pop_close {
    position: absolute;
    top: 26rpx;
    right: 20rpx;
    width: 42rpx;
    height: 42rpx;
    background: #f2f2f2;
    border-radius: 6rpx 6rpx 6rpx 6rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

//体重时间确认
.weight_time_verify {
  font-family: PingFang SC, PingFang SC;
  margin: 50rpx auto;
  width: 542rpx;
  height: 86rpx;
  background: #a28aff;
  border-radius: 106rpx 106rpx 106rpx 106rpx;
  font-size: 28rpx;
  color: #ffffff;
  text-align: center;
  line-height: 86rpx;
}
//增长量弹框
.warn_box {
  width: 510rpx;
  background: #ffffff;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 50rpx;
  .warn_main {
    width: 410rpx;
    font-weight: 500;
    font-size: 28rpx;
    color: #333333;
    text-align: center;
    margin-bottom: 4rpx;
    line-height: 1.5;
  }
  .custom_style {
    width: 338rpx;
    height: 54rpx;
    background: #a28aff;
    border-radius: 106rpx 106rpx 106rpx 106rpx;
    margin-top: 30rpx;
  }
}
</style>
